//
//  ZQMainViewController.swift
//  新浪微博
//
//  Created by huami on 2019/10/10.
//  Copyright © 2019 huami. All rights reserved.
//

import UIKit
/// 主控制器
class ZQMainViewController: UITabBarController {
    // 定时器
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.cz_random()
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        
        /// 销毁时钟
        timer?.invalidate()
        
        /// 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func userLogin(n: Notification) {
        print("用户登录通知\(n)")
    }
    
    // landscape 横屏
    // portrait   竖屏
    // 好处 ： 使用代码控制设备的方向，可以在需要横屏的时候，单独处理
    // 设置支持的方向后，当前的控制前及其子控制器都会遵守这个方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // MARK: 监听方法
    // 撰写微博
    // @objc 允许这个函数通过oc运行机制可以调用
    @objc private func composeStatus() {
        print("撰写微博")
        
        // 测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
    // MARK: -私有方法
    private lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
}


// MARK： - 定时器的相关方
extension ZQMainViewController {
    /// 定义时钟
    private func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 时钟的触发方法
    @objc private func updateTimer() {
        if !ZQNetWorkManager.shared.userLogin {
            return
        }
        
        ZQNetWorkManager.shared.unreadCount { (count: Int) in
//            print("监测到 \(count) 条微博")
            // 设置首页的 tabBarItem 的badgeNumber
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            // 设置 app 的 badgenumber, 从iOS8之后要用户授权才可以显示
            UIApplication.shared.applicationIconBadgeNumber = count
         }
    }
}

// MARK： - UITabBarControllerDelegate
extension ZQMainViewController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要点击的是\(viewController)".unicodeScalars)
        
        // 将要点击的idx
        let idx = (children as NSArray).index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击的是首页")
            
            let nav = children[0] as! UINavigationController
            let vc = nav.children[0] as! ZQHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -88), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                vc.loadData()
            }
        }
        
        return !viewController .isMember(of: UIViewController.self)
    }
}

// 可以把相近的功能函数，放在一个extension中，便于代码维护
// 注意：和OC的分类一样，extension 中不能定义属性
// MARK： - 设置界面
extension ZQMainViewController {
    
    func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        // 设置按钮的宽度
        let count = CGFloat(viewControllers!.count)
        let w = tabBar.bounds.width / count
        
        // 正数向内缩进，负数像外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    private func setupChildControllers() {
        
        // 0. 获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断data是否内容，如果没有，说明本地沙盒没有文件
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        // 1.路径 2.加载nsdata 3.反序列化数组
        guard let array = try? JSONSerialization.jsonObject(with:data! as Data , options: []) as? [[String : AnyObject]]  else {
            return
        }
        
        
        
        // 将数组转化为json查看
        //        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        //        (data as NSData).write(toFile: "/Users/huami/Documents/ss/main.json", atomically: true)
        
        // 验证plist格式是否正确
        //        (array as NSArray).write(toFile: "/Users/huami/Documents/ss/demo.plist", atomically: true)
        // 遍历数组，循环创建控制器数组
        var arrayM  = [UIViewController]()
        for dict  in array {
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        
        // 设置tabbar 的子控制器
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    /// - Parameter dict: 信息字典
    /// - returns: 子控制器
    private  func controller(dict:[String : AnyObject]) -> UIViewController {
        // 1. 取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? ZQBaseViewController.Type,
            let visitorDict = dict["vistorInfo"] as? [String: String]
            else {
                return UIViewController()
        }
        
        // 2. 创建视图控制器
        // 1> 将clsName 转化成cls
        let vc = cls.init()
        vc.title = title
        
        // 设置访客的字典
        vc.visitorInfoDictionay = visitorDict
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        
        vc.tabBarItem.setTitleTextAttributes(
            [NSAttributedString.Key.foregroundColor:UIColor.orange],
            for: .highlighted)
        
        vc.tabBarItem.setTitleTextAttributes(
            [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 12)],
            for: UIControl.State.init(rawValue: 0))
        let nav = ZQNavigationController(rootViewController: vc)
        return nav
    }
}
